package com.zjut.an.acquisitionhistory.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.zjut.an.acquisitionhistory.dao.AnAcquisitionHistory;
import com.zjut.an.util.module.PageModule;


/**
 * A data access object (DAO) providing persistence and search support for
 * AnAcquisitionHistory entities. Transaction control of the save(), update()
 * and delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see com.zjut.an.acquisitionhistory.dao.AnAcquisitionHistory
 * @author MyEclipse Persistence Tools
 */

public class AnAcquisitionHistoryDAO extends HibernateDaoSupport {
	private static final Logger log = LoggerFactory
			.getLogger(AnAcquisitionHistoryDAO.class);
	// property constants
	public static final String HI_ID = "hiId";
	public static final String CHANNEL_URL = "channelUrl";
	public static final String CONTENT_URL = "contentUrl";
	public static final String TITLE = "title";
	public static final String DESCRIPTION = "description";
	public static final String AC_ID = "acId";
	public static final String NE_ID = "neId";

	protected void initDao() {
		// do nothing
	}

	public void sort(Criteria criteria, String sort, String order) {
		if (sort!=null && order!=null) {
			if (order.equals("asc")) {
				criteria.addOrder(Order.asc(sort));
			} else {
				criteria.addOrder(Order.desc(sort));
			}
		} else {
			criteria.addOrder(Order.desc(HI_ID));			
		}
	}
	
	public void save(AnAcquisitionHistory transientInstance) {
		log.debug("saving AnAcquisitionHistory instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(AnAcquisitionHistory persistentInstance) {
		log.debug("deleting AnAcquisitionHistory instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public AnAcquisitionHistory findById(java.lang.Integer id) {
		log.debug("getting AnAcquisitionHistory instance with id: " + id);
		try {
			AnAcquisitionHistory instance = (AnAcquisitionHistory) getHibernateTemplate()
					.get(
							"com.zjut.an.acquisitionhistory.dao.AnAcquisitionHistory",
							id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(AnAcquisitionHistory instance) {
		log.debug("finding AnAcquisitionHistory instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding AnAcquisitionHistory instance with property: "
				+ propertyName + ", value: " + value);
		try {
			String queryString = "from AnAcquisitionHistory as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByChannelUrl(Object channelUrl) {
		return findByProperty(CHANNEL_URL, channelUrl);
	}

	public List findByContentUrl(Object contentUrl) {
		return findByProperty(CONTENT_URL, contentUrl);
	}

	public List findByTitle(Object title) {
		return findByProperty(TITLE, title);
	}

	public List findByDescription(Object description) {
		return findByProperty(DESCRIPTION, description);
	}

	public List findByAcId(Object acId) {
		return findByProperty(AC_ID, acId);
	}

	public List findByNeId(Object neId) {
		return findByProperty(NE_ID, neId);
	}

	public List findAll() {
		log.debug("finding all AnAcquisitionHistory instances");
		try {
			String queryString = "from AnAcquisitionHistory";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public AnAcquisitionHistory merge(AnAcquisitionHistory detachedInstance) {
		log.debug("merging AnAcquisitionHistory instance");
		try {
			AnAcquisitionHistory result = (AnAcquisitionHistory) getHibernateTemplate()
					.merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(AnAcquisitionHistory instance) {
		log.debug("attaching dirty AnAcquisitionHistory instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(AnAcquisitionHistory instance) {
		log.debug("attaching clean AnAcquisitionHistory instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
	
	public boolean checkExistByProperties(boolean isTitle, String value){
		DetachedCriteria criteria = DetachedCriteria.forClass(AnAcquisitionHistory.class);
		if (isTitle) {
			criteria.add(Restrictions.eq("title", value));
		} else {
			criteria.add(Restrictions.eq("contentUrl", value));
		}
		return getHibernateTemplate().findByCriteria(criteria).size() > 0 ? true : false;
	}

	public static AnAcquisitionHistoryDAO getFromApplicationContext(
			ApplicationContext ctx) {
		return (AnAcquisitionHistoryDAO) ctx.getBean("AnAcquisitionHistoryDAO");
	}
	
	@SuppressWarnings("unchecked")
	public PageModule findByInstance(final int pageNumber ,final int pageSize, String sort, String order, final AnAcquisitionHistory obj){
		try {
			int startIndex = (pageNumber - 1) * pageSize;
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			List list;
			Criteria criteria = session.createCriteria(AnAcquisitionHistory.class);
			
			if (!isEmpty(obj.getChannelUrl())) {
				criteria.add(Restrictions.eq(CHANNEL_URL, obj.getChannelUrl()));
			}
			if (!isEmpty(obj.getContentUrl())) {
				criteria.add(Restrictions.eq(CONTENT_URL, obj.getContentUrl()));
			}
			if (!isEmpty(obj.getDescription())) {
				criteria.add(Restrictions.eq(DESCRIPTION, obj.getDescription()));
			}
			if (null!=obj.getAcId()) {
				criteria.add(Restrictions.eq(AC_ID, obj.getAcId()));
			}
			if (null!=obj.getNeId()) {
				criteria.add(Restrictions.eq(NE_ID, obj.getNeId()));
			}
			
			this.sort(criteria, sort, order);
			
			criteria.setFirstResult(startIndex);
			criteria.setMaxResults(pageSize);
			list = criteria.list();
			session.close();
			return new PageModule(pageNumber, pageSize, countByInstance(obj), list);
		} catch (RuntimeException re) {
			log.error("findByInstance failed", re);
			throw re;
		}
	}
	
	public int countByInstance(final AnAcquisitionHistory obj) {
		log.debug("finding the number of AnAcquisitionHistory instance");
		try {
			int count = 0;
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			Criteria criteria = session.createCriteria(AnAcquisitionHistory.class);

			if (!isEmpty(obj.getChannelUrl())) {
				criteria.add(Restrictions.eq(CHANNEL_URL, obj.getChannelUrl()));
			}
			if (!isEmpty(obj.getContentUrl())) {
				criteria.add(Restrictions.eq(CONTENT_URL, obj.getContentUrl()));
			}
			if (!isEmpty(obj.getDescription())) {
				criteria.add(Restrictions.eq(DESCRIPTION, obj.getDescription()));
			}
			if (null!=obj.getAcId()) {
				criteria.add(Restrictions.eq(AC_ID, obj.getAcId()));
			}
			if (null!=obj.getNeId()) {
				criteria.add(Restrictions.eq(NE_ID, obj.getNeId()));
			}
			
			count = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();
			session.close();
			return count;
		} catch (RuntimeException re) {
			log.error("find the number of AnAcquisitionHistory instance failed", re);
			throw re;
		}
	}

	private boolean isEmpty(String value) {
		if (value==null || value.trim().length()==0) {
			return true;
		}
		return false;
	}
	
	@SuppressWarnings("unchecked")
	public List<AnAcquisitionHistory> findByHql(final int pageNumber ,final int pageSize, final String hql, final Object[] values){
		log.debug("finding AnAcquisitionHistory instance by hql");
	    return (List<AnAcquisitionHistory>) super.getHibernateTemplate().execute(new HibernateCallback(){
	        public Object doInHibernate(Session session) throws HibernateException, SQLException {
	            Query query=session.createQuery(hql);
	            if (values != null) {// 为hql语句传入参数
					for (int i = 0; i < values.length; i++) {
						query.setParameter(i, values[i]);
					}
				}
	            return query.setFirstResult((pageNumber-1)*pageSize).setMaxResults(pageSize).list();
	        }
	    });
	}

	@SuppressWarnings("unchecked")
	public int findCountByHql(final String hql, final Object[] values) {
		log.debug("finding the number of AnAcquisitionHistory instance");
		try {
			return (Integer) super.getHibernateTemplate().execute(new HibernateCallback(){
		        public Object doInHibernate(Session session) throws HibernateException, SQLException {
		            Query query=session.createQuery(hql);
		            if (values != null) {// 为hql语句传入参数
						for (int i = 0; i < values.length; i++) {
							query.setParameter(i, values[i]);
						}
					}
					return ((Long)query.uniqueResult()).intValue();
		        }
		    });
		} catch (RuntimeException re) {
			log.error("find the number of AnAcquisitionHistory instance failed", re);
			throw re;
		}
	}
	
}